package cn.fu.simplemail;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message.RecipientType;
import javax.mail.internet.MimeUtility;

import org.codemonkey.simplejavamail.Mailer;
import org.codemonkey.simplejavamail.TransportStrategy;
import org.codemonkey.simplejavamail.email.AttachmentResource;
import org.codemonkey.simplejavamail.email.Email;

/**
 * @Title: MailTest.java
 * @Package cn.fu.simplemail
 * @Description: TODO(用一句话描述该文件做什么)
 * @author zhangxiaofu
 * @Company www.viewhigh.com
 * @date 2016年9月19日 下午4:42:13
 * @version V1.0
 */
public class MailTest {
	/**
	 * Just run as Java application, but remember to set the JVM arguments
	 * first.
	 * 
	 * @param args
	 *            should be empty, this demo uses JVM arguments only
	 *            (-Dhost=value etc.).
	 * @throws UnsupportedEncodingException
	 */
	public static void main(final String[] args) throws Exception {
		final Email email = new Email();
		email.setFromAddress("fromName", "fromName@163.com");
		email.addRecipient("toName", "toName@163.com", RecipientType.TO);
		email.setText("We should meet up!");
		email.setTextHTML("<b>We should meet up!</b>");
		email.setSubject("服务科室1");
		
		//添加附件的二种方式，此种有bug,指定附件名称无效。带服务附件乱或bin
		/*String fileName = MimeUtility.encodeText("服务.txt", "utf-8", null);
		DataSource dataSource = new FileDataSource(new File("D:/服务.xlsx"));
		email.addAttachment(fileName, dataSource);*/
		
		//text/plain 可随意指定。 必须有
		/*String fileName = MimeUtility.encodeText("服务.txt", "utf-8", null);
		InputStream inputStream = new FileInputStream(new File("D:/服务.txt"));
		byte data[] = InputStreamToByte(inputStream);
		email.addAttachment(fileName, data, "text/plain");*/
		
		String fileName = MimeUtility.encodeText("服务.xlsx", "utf-8", null);
		InputStream inputStream = new FileInputStream(new File("D:/服务.xlsx"));
		byte data[] = InputStreamToByte(inputStream);
		email.addAttachment(fileName, data, "ww/ww");
		sendMail(email);
	}

	private static void sendMail(final Email email) {
		final String host = "smtp.163.com";
		final int port = 25;
		final String username = "userName@163.com";
		final String password = "password";
		new Mailer(host, port, username, password, null).sendMail(email);
	}

	//将流转byte[]
	private static byte[] InputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int ch;
		while ((ch = is.read(buffer)) != -1) {
			bytestream.write(buffer, 0, ch);
		}
		byte data[] = bytestream.toByteArray();
		bytestream.close();
		return data;
	}
}
